package com.tanhua.server;

import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.exception.BusinessException;
import com.tanhua.interceptor.UserHolder;
import com.tanhua.model.UserInfo;
import com.tanhua.mondb.Movement;
import com.tanhua.vo.ErrorResult;
import com.tanhua.vo.MovementsVo;
import com.tanhua.vo.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class MovementsService {

    @DubboReference
    private MovementApi movementApi;
    @Autowired
    private OssTemplate ossTemplate;
    @DubboReference
    private UserInfoApi userInfoApi;
   /*
        发布个人动态
   * */
    public void publishMovements(Movement movement, MultipartFile[] imageContent) throws BusinessException, IOException {
        //判断发布内容是否为空
        if(StringUtils.isEmpty(movement.getTextContent())){
                throw  new BusinessException(ErrorResult.contentError());
        }
        //获取当前用户的id
        Long userId = UserHolder.getUserId();
        //将图片上传致阿里云
        ArrayList<String> Medias = new ArrayList<>();
        for(MultipartFile multipartFile :imageContent){
            String upload = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
            Medias.add(upload);
        }
        //封装成一个圈子对象
        movement.setUserId(userId);
        movement.setMedias(Medias);
        //保存圈子里面
        movementApi.publish(movement);
    }
    /*
    * 查看我的动态
    * */
    public PageResult movementsByUserId(Long userId, Integer page, Integer pageSize) {
        //根据userid将我的发布的动态进行分页查询，封装成结果页，结果页中的items集合保存一个一个的Movement对象
       PageResult pr = movementApi.movementsByUserId(userId,page,pageSize);

        List<Movement> items = (List<Movement>) pr.getItems();

        if(items==null){
            return  pr;
        }
        UserInfo userInfo = userInfoApi.findById(userId);

        ArrayList<MovementsVo> vos = new ArrayList<>();
        for (Movement item : items){
            MovementsVo vo = MovementsVo.init(userInfo, item);
            vos.add(vo);
        }
        pr.setItems(vos);
        return pr;
    }
}
